import React, { Component } from "react";
import { Table, Modal, Button, Form, Input } from "antd";
import { connect } from "dva";
import SampleChart from "../../components/SampleChart";

const mapStateToProps = ({ cards, loading }) => ({
  ...cards,
  cardsLoading: loading.effects["cards/queryList"]
});

class List extends Component {
  state = {
    visible: false,
    statisticVisible: false,
    id: 1
  };
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: "cards/queryList" });
  }
  showStatistic = id => {
    this.props.dispatch({
      type: "cards/getStatistic",
      payload: id
    });
    // 更新 state，弹出包含图表的对话框
    this.setState({ id, statisticVisible: true });
  };

  handleStatisticCancel = () => {
    this.setState({
      statisticVisible: false
    });
  };
  columns = [
    {
      title: "名称",
      dataIndex: "name"
    },
    {
      title: "描述",
      dataIndex: "desc"
    },
    {
      title: "链接",
      dataIndex: "url",
      render: value => <a href={value}>{value}</a>
    },
    {
      title: "",
      dataIndex: "_",
      render: (_, { id }) => {
        return (
          <Button
            onClick={() => {
              this.showStatistic(id);
            }}
          >
            图表
          </Button>
        );
      }
    }
  ];

  render() {
    const { cardsList, cardsLoading, form, dispatch, statistic } = this.props;
    const { getFieldDecorator } = form;
    const { statisticVisible, id } = this.state;
    return (
      <div>
        <Table
          columns={this.columns}
          dataSource={cardsList}
          loading={cardsLoading}
          rowKey="name"
        />
        <Button onClick={() => this.setState({ visible: true })}>新建</Button>
        <Modal
          visible={this.state.visible}
          title="新建记录"
          onOk={() => {
            form.validateFields((err, values) => {
              if (!err) {
                dispatch({ type: "cards/addOne", payload: values });
                this.setState({ visible: false });
              }
            });
          }}
          onCancel={() => this.setState({ visible: false })}
        >
          <Form>
            <Form.Item label="名称">
              {getFieldDecorator("name", {
                rules: [{ required: true }]
              })(<Input />)}
            </Form.Item>
            <Form.Item label="描述">
              {getFieldDecorator("desc")(<Input />)}
            </Form.Item>
            <Form.Item label="链接">
              {getFieldDecorator("url", {
                rules: [{ type: "url" }]
              })(<Input />)}
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          visible={statisticVisible}
          footer={null}
          onCancel={this.handleStatisticCancel}
        >
          {/* <SampleChart data={statistic[id]} /> */}
        </Modal>
      </div>
    );
  }
}

export default connect(mapStateToProps)(Form.create()(List));
